package com.feilong.edgeAI.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2024/1/13 15:02
 */
public class FileUtil {
    private static final String TAG = "FileUtil";
    public final static String EXAGEAR_PATH = "exagear";
    public static boolean copyFileFromAssets(Context context, String fileName) throws IOException {
        InputStream input = null;
        OutputStream output = null;

        try {
            // 打开输入流并指定要复制的文件名
            input = context.getAssets().open(fileName);

            // 构造输出路径为SD卡根目录下的同名文件
            String filePath = Environment.getExternalStorageDirectory() + "/" + fileName;
            output = new FileOutputStream(filePath);

            byte[] buffer = new byte[4096];
            int length;

            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            output.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }

    public static Map<String, String> parseIniFile(String filePath) {
        Map<String, String> iniMap = new HashMap<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 忽略空行和注释行
                if (line.trim().isEmpty() || line.startsWith("#")) {
                    continue;
                }

                // 解析键值对
                String[] keyValue = line.split("=", 2);
                if (keyValue.length == 2) {
                    iniMap.put(keyValue[0].trim(), keyValue[1].trim());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return iniMap;
    }

    public static void copy(){
        // 获取源文件路径和目标文件路径
        String srcPath = "/data/data/com.feilong.edgeAI/";
//        String srcPath = "/data/data/com.termux/";
        String dstPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator  + "termux/";

        try {
            // 检查外部存储是否可用
//            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File srcFile = new File(srcPath);
                File dstFile = new File(dstPath);

                // 确保目标目录存在
                if (!dstFile.getParentFile().exists()) {
                    dstFile.getParentFile().mkdirs();
                }

                // 复制文件，这里假设你有对srcPath的访问权限（可能需要root）
                FileInputStream inStream = new FileInputStream(srcFile);
                FileOutputStream outStream = new FileOutputStream(dstFile);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = inStream.read(buffer)) > 0) {
                    outStream.write(buffer, 0, length);
                }

                inStream.close();
                outStream.close();

                // 复制成功后可以进行相应的提示或处理
//            } else {
//                Log.e("FileCopy", "External storage is not mounted.");
//            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void appendText(String filePath, String textToAppend) {
        try {
            // 创建一个File对象，指向要追加文本的txt文件
            File file = new File(filePath);

            // 创建一个FileWriter对象，构造函数自动打开流并指向文件的末尾
            BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));

            // 使用BufferedWriter向文件追加文本
            writer.write(textToAppend);
            writer.newLine(); // 添加换行符，如果不希望换行则可以省略这行

            // 关闭writer，确保所有数据都已经写入文件
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
            // 处理文件读写异常
        }
    }

    public static void copyFolderToExternalStorage(Context context, String sourceFolderPath, String destinationFolderPath) {

        File sourceDir = new File(sourceFolderPath);
        File destDir = new File(Environment.getExternalStorageDirectory(), destinationFolderPath);

        try {
            if (!destDir.exists()) {
                destDir.mkdirs();
            }

            copyFolderRecursively(sourceDir, destDir);
            Toast.makeText(context, "文件夹复制完成", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(context, "文件夹复制失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private static void copyFolderRecursively(File src, File dst) throws IOException {
        Log.d(TAG, "copyFolderRecursively: "+src.getAbsolutePath());
        if (src.isDirectory()) {
            if (!dst.exists()) {
                dst.mkdir();
            }

            for (String fileName : src.list()) {
                File srcFile = new File(src, fileName);
                File destFile = new File(dst, fileName);
                copyFolderRecursively(srcFile, destFile);
            }
        } else {
            FileInputStream inStream = new FileInputStream(src);
            FileOutputStream outStream = new FileOutputStream(dst);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }

            inStream.close();
            outStream.close();
        }
    }
}
